//
//  UIImageView+WJ.m
//  BeDeJie
//
//  Created by jerry on 2017/2/2.
//  Copyright © 2017年 jerry. All rights reserved.
//

#import "UIImageView+WJ.h"
#import <AFNetworkReachabilityManager.h>

@implementation UIImageView (WJ)

- (void)setOriginImage:(NSString *)originImageURL
        thumbnailImage:(NSString *)thumbnailImageURL
           placeholder:(UIImage *)placeholder
             completed:(SDWebImageCompletionBlock)completedBlock {
    
    // 缓存图片的key后面增加后缀
//    [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) {
//        // 所有缓存图片的key后面都有个-xmg后缀
//       return [NSString stringWithFormat:@"%@-xmg", url.absoluteString];
//    }];
    
    // 获得原图（SDWebImage的图片缓存是用图片的url字符串作为key）
    UIImage *originImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:originImageURL];
    // 获得缩略图
    UIImage *thumbnailImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:thumbnailImageURL];
    // 3G\4G网络下时候要下载原图
    BOOL downloadOriginImageWhen3GOr4G = YES;
    if (originImage) { // 原图已经被下载过
         [self sd_setImageWithURL:[NSURL URLWithString:originImageURL] placeholderImage:placeholder completed:completedBlock];
    } else { // 原图并未下载过
        // 根据网络状态来加载图片
        //1.创建网络状态监测管理者
        AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
        //2.开启监听网络
        [mgr startMonitoring];
        //3.监听状态改变
        [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch(status) {
                case AFNetworkReachabilityStatusReachableViaWiFi:
                    [self sd_setImageWithURL:[NSURL URLWithString:originImageURL] placeholderImage:placeholder completed:completedBlock];
                    break;
                    
                case AFNetworkReachabilityStatusReachableViaWWAN:
#warning downloadOriginImageWhen3GOr4G配置项的值需要从沙盒里面获取
                    if (downloadOriginImageWhen3GOr4G) {
                        [self sd_setImageWithURL:[NSURL URLWithString:originImageURL] placeholderImage:placeholder completed:completedBlock];
                    } else {
                        [self sd_setImageWithURL:[NSURL URLWithString:thumbnailImageURL] placeholderImage:placeholder completed:completedBlock];
                    }
                    break;
                    
                case AFNetworkReachabilityStatusUnknown:
                case AFNetworkReachabilityStatusNotReachable:
                    if (thumbnailImage) { // 缩略图已经被下载过
                        [self sd_setImageWithURL:[NSURL URLWithString:thumbnailImageURL] placeholderImage:placeholder completed:completedBlock];
                    } else { // 没有下载过任何图片
                        // 占位图片;
                        [self sd_setImageWithURL:nil placeholderImage:placeholder completed:completedBlock];
                    }
                    break;
            }
        }];
        //4.关闭网络监听
        [mgr stopMonitoring];
    }
}

@end
